package com.media.appmedia.activity;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import org.json.JSONException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.media.appmedia.R;
import com.media.appmedia.base.BaseActivity;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.util.FileUtils;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;
import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.RenrenShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.EmailHandler;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.RenrenSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

/**
 * 
 * <pre>
 * 业务名:
 * 功能说明:  推广下线 ，分享  链接  二维码
 * 
 * 编写日期:	2014-11-7
 * 作者:	 Rose
 * 
 * 历史记录
 * 1、修改日期：
 *    修改人：Rose
 *    修改内容：充实分享内容和业务逻辑以及二维码的生成与保存
 * </pre>
 */
@SuppressWarnings("deprecation")
public class ShareActivity2 extends BaseActivity implements OnClickListener {
	private boolean isShare = false;
	private boolean isLoad = true;
	private Bitmap bitmaps;
	private ImageButton mImageButtoncopy;
	private ImageButton mImageButtonerweima;
	private ImageButton mImageButtonfx;
	@ViewInject(R.id.imageButtonerweima)
	private ImageButton imageView;
	@ViewInject(R.id.textView88)
	private TextView textViewUrl;
	private String myUrl;
	private String shareContent = "我就是分享的内容";
	private final String SHARE_TITLE = "赚乐淘";
	final UMSocialService mController = UMServiceFactory.getUMSocialService(
			"com.umeng.share", RequestType.SOCIAL);

	Map<String, SHARE_MEDIA> mPlatformsMap = new HashMap<String, SHARE_MEDIA>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.share_layout);
		myUrl = getMyShare(PhoneInfoUtils.getIMEI(getApplicationContext()));
		getShareContent(PhoneInfoUtils.getIMEI(getApplicationContext()));
		initView();
		ViewUtils.inject(this);
		// 个人推广链接的显示内容，无实际意义
		// textViewUrl.setText(myUrl);
		createQRImage(myUrl);

		// initPlatformMap();
	}

	private void initView() {
		mImageButtoncopy = (ImageButton) findViewById(R.id.imageButtoncoyp);
		mImageButtonerweima = (ImageButton) findViewById(R.id.Buttonerweima);
		mImageButtonfx = (ImageButton) findViewById(R.id.imageButtonfx);
		mImageButtoncopy.setOnClickListener(this);
		mImageButtonerweima.setOnClickListener(this);
		mImageButtonfx.setOnClickListener(this);
	}

	/**
	 * 初始化SDK，添加一些平台
	 */
	private void initSocialSDK() {
		mController.setShareContent(shareContent);
		// 图片分享内容
		mController.setShareMedia(new UMImage(ShareActivity2.this, bitmaps));
		// 设置新浪SSO handler
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		// 添加QQ空间平台 OK
		QZoneSsoHandler qzoneHandler = new QZoneSsoHandler(ShareActivity2.this,
				"1104418605", "Zi1vi8qRsmZps38O");
		qzoneHandler.addToSocialSDK();
		// 添加QQ平台 OK
		UMQQSsoHandler qqHandler = new UMQQSsoHandler(ShareActivity2.this,
				"1104418605", "Zi1vi8qRsmZps38O");
		qqHandler.addToSocialSDK();
		// 微信平台
		String appID = "wxdf0102bc9be35819";
		String appSecret = "44ab6b87aeada08886a308358d52dd6f";
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(getApplicationContext(), appID,
				appSecret);
		wxHandler.addToSocialSDK();
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(getApplicationContext(),
				appID, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		// 人人网
		RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(
				ShareActivity2.this, "273006",
				"20c2e3559525477ba47c1ad50bcc1cf1",
				"2360e8dafdad434780c8a08516d32adb");
		mController.getConfig().setSsoHandler(renrenSsoHandler);
		// 人人网分享内容
		RenrenShareContent renrenShareContent = new RenrenShareContent();
		renrenShareContent.setShareContent(shareContent);
		renrenShareContent.setShareImage(new UMImage(getApplicationContext(),
				bitmaps));
		renrenShareContent.setTargetUrl(myUrl);
		mController.setAppWebSite(SHARE_MEDIA.RENREN, "http://www.sgfc88.com/");
		renrenSsoHandler.addToSocialSDK();
		mController.setShareMedia(renrenShareContent);
		// 添加email
		EmailHandler emailHandler = new EmailHandler();
		emailHandler.setTargetUrl(myUrl);
		emailHandler.addToSocialSDK();

		// 设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		// 设置分享文字
		weixinContent.setShareContent(shareContent);
		// 设置title
		weixinContent.setTitle("升官发财");
		// 设置分享内容跳转URL
		weixinContent.setTargetUrl(myUrl);
		// 设置分享图片
		weixinContent.setShareImage(new UMImage(getApplicationContext(),
				bitmaps));
		mController.setShareMedia(weixinContent);

		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia.setShareContent(shareContent);
		// 设置朋友圈title
		circleMedia.setTargetUrl(myUrl);
		circleMedia.setTitle("赚乐淘\n" + shareContent);
		circleMedia
				.setShareImage(new UMImage(getApplicationContext(), bitmaps));
		mController.setShareMedia(circleMedia);

		// 设置QQ空间分享内容
		QZoneShareContent qzone = new QZoneShareContent();
		qzone.setShareContent(shareContent);
		qzone.setTargetUrl(myUrl);
		qzone.setTitle(SHARE_TITLE);
		qzone.setShareImage(new UMImage(getApplicationContext(), bitmaps));
		// qzone.setShareImage(urlImage);
		mController.setShareMedia(qzone);

		// 设置QQ分享内容
		QQShareContent qqShareContent = new QQShareContent();
		// 设置分享文字
		qqShareContent.setShareContent(shareContent);
		// 设置分享title
		qqShareContent.setTitle(SHARE_TITLE);
		// 设置分享图片
		qqShareContent.setShareImage(new UMImage(getApplicationContext(),
				bitmaps));
		// 设置点击分享内容的跳转链接
		qqShareContent.setTargetUrl(myUrl);
		mController.setShareMedia(qqShareContent);
		// 设置新浪微博分享内容
		SinaShareContent sinaContent = new SinaShareContent();
		sinaContent.setShareContent(shareContent);
		sinaContent.setTitle(SHARE_TITLE);
		sinaContent.setTargetUrl(myUrl);
		sinaContent
				.setShareImage(new UMImage(getApplicationContext(), bitmaps));
		mController.setShareMedia(sinaContent);

		mController.getConfig().registerListener(new SnsPostListener() {

			@Override
			public void onStart() {
			}

			@Override
			public void onComplete(SHARE_MEDIA platform, int stCode,
					SocializeEntity entity) {
				if (stCode == 200) {
					String name = platform.name();
					int type = 0;
					if (name.equals("SINA")) {
						type = 1;
					} else if (name.equals("QZONE")) {
						type = 6;
					} else if (name.equals("QQ")) {
						type = 24;
					} else if (name.equals("TENCENT")) {
						type = 2;
					} else if (name.equals("EMAIL")) {
						type = 18;
					} else if (name.equals("RENREN")) {
						type = 7;
					} else if (name.equals("WEIXIN")) {
						type = 22;
					} else if (name.equals("WEIXIN_CIRCLE")) {
						type = 23;
					}
					putShareGolds(
							PhoneInfoUtils.getIMEI(getApplicationContext()),
							"3", type + "");
				} else {
					Toast.makeText(ShareActivity2.this,
							"分享失败 : error code : " + stCode, Toast.LENGTH_SHORT)
							.show();
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.imageButtoncoyp:
			// 对邀请链接进行复制到剪切板(api11之前使用已过时的方法 )
			ClipboardManager copy = (ClipboardManager) ShareActivity2.this
					.getSystemService(Context.CLIPBOARD_SERVICE);
			copy.setText(myUrl);
			if (!MethodUtils.isEmpty(copy.getText().toString().trim())) {
				// 提示复制成功
				AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(
						ShareActivity2.this);
				alertbBuilder
						.setTitle("提示")
						.setMessage("邀请链接复制成功")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								}).create();
				alertbBuilder.show();
			}

			break;
		case R.id.Buttonerweima:
			// 保存二维码图片到本地sdcard中
			if (!isLoad) {
				ToastUtils.show(getApplicationContext(), "您刚保存完成，请勿频繁操作！");
			} else {
				new MyThread(new SetDialog() {

					@Override
					public void setDialog(boolean flage) {
						String content = "";
						if (flage) {
							content = "您的二维码保存成功!\n(存储在Downlad文件夹下)";
							isLoad = false;
						} else {
							content = "二维码保存失败，请检查您的存储设备是否可用";
						}
						AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(
								ShareActivity2.this);
						alertbBuilder
								.setTitle("提示")
								.setMessage(content)
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.cancel();
											}
										}).create();
						alertbBuilder.show();
					}
				}).run();
			}

			break;
		case R.id.imageButtonfx:
			Log.i("mytag", "-->test t_share");
			// 判断分享内容是否已经下载完成
			if (!isShare) {
				ToastUtils.show(getApplicationContext(), "请检查您的网络!");
				return;
			}
			// showCustomUI(false);
			mController.getConfig().setPlatforms(SHARE_MEDIA.QZONE,
					SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ,
					SHARE_MEDIA.EMAIL, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.RENREN,
					SHARE_MEDIA.TENCENT, SHARE_MEDIA.SINA);
			mController.openShare(ShareActivity2.this, false);
			break;

		default:
			break;
		}
	}

	/**
	 * 
	 * 方法说明：二维码生成器
	 * 
	 * @param url
	 *            需要生成URL的二维码
	 */
	// 要转换的地址或字符串,可以是中文
	public void createQRImage(String url) {
		int QR_WIDTH = 300;
		int QR_HEIGHT = 300;

		try {
			// 判断URL合法性
			if (url == null || "".equals(url) || url.length() < 1) {
				return;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(url,
					BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
			int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
			// 下面这里按照二维码的算法，逐个生成二维码的图片，
			// 两个for循环是图片横列扫描的结果
			for (int y = 0; y < QR_HEIGHT; y++) {
				for (int x = 0; x < QR_WIDTH; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * QR_WIDTH + x] = 0xff000000;
					} else {
						pixels[y * QR_WIDTH + x] = 0xffffffff;
					}
				}
			}
			// 生成二维码图片的格式，使用ARGB_8888
			Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
			// 显示到一个ImageView上面
			imageView.setImageBitmap(bitmap);
			bitmaps = bitmap;
		} catch (WriterException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 作者: Rose 业务名: 功能说明: 回调接口，用于保存成功后回调 编写日期: 2014-12-3
	 * 
	 */
	public interface SetDialog {
		void setDialog(boolean flage);
	}

	/**
	 * 
	 * 作者: Rose 业务名: 功能说明: 存储二维码图片操作 编写日期: 2014-12-3
	 * 
	 */
	class MyThread {
		private final String imagepath = "ss/sgfc88.jpg";
		private SetDialog dialog;

		public MyThread(SetDialog dialog) {
			this.dialog = dialog;
		}

		private byte[] getByte(Bitmap bitmap) {
			ByteArrayOutputStream output = new ByteArrayOutputStream();// 初始化一个流对象
			bitmap.compress(CompressFormat.PNG, 100, output);// 把bitmap100%高质量压缩
																// 到 output对象里

			bitmap.recycle();// 自由选择是否进行回收

			byte[] result = output.toByteArray();// 转换成功了
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		public void run() {
			// 图片写入缓存
			boolean b1 = false;
			if (imagepath != null) {
				byte[] b = getByte(bitmaps);
				if (b != null && b.length != 0) {
					// 图片缓存到sd卡,调用fileUtils写入工具类
					if (FileUtils.isStateUseful()) {// 判断sd卡是否能用
						b1 = FileUtils.writeImageToSdcard(b, imagepath);
						if (b1) {
							System.out.println("写入成功");
						} else {
							System.out.println("写入失败");
						}
					} else {
						System.out.println("sdcard不可用");
					}
				}
			} else {
				System.out.println("没有图片");
			}
			dialog.setDialog(b1);
		}
	}


	private void getShareContent(String biaoshifu) {
		ProtocolService.getShareContent(biaoshifu,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							if (obj.getInt("message") == 1) {
								shareContent = obj.getString("content");
								isShare = true;
								initSocialSDK();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getApplicationContext(),
								R.string.phone_verify_send_fail);
					}
				});
	}

	@OnClick({ R.id.come_back})
	public void back(View v) {
		ShareActivity2.this.finish();
	}

	private void putShareGolds(String biaoshifu, String share_record_content,
			String share_record_type) {
		ProtocolService.putShareGold(biaoshifu, share_record_content,
				share_record_type, new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							if (obj.getInt("message") == 1) {
								shareContent = obj.getString("content");
								isShare = true;
								initSocialSDK();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getApplicationContext(),
								R.string.phone_verify_send_fail);
					}
				});
	}
}
